package com.sxj.shop.service.proxy;

import com.sxj.shop.entity.User;
import com.sxj.shop.exception.*;
import com.sxj.shop.factory.ObjectFactory;
import com.sxj.shop.service.UserService;
import com.sxj.shop.tran.TransactionManager;

/**
 * @author 石小俊
 * @date 2023年12月2023/12/5日 18:28
 * 交叉业务逻辑:实现与具体业务无关的一些额外功能
 * 例如:事务、日志、安全处理
 */
public class UserServiceProxy implements UserService {

    private TransactionManager tran = (TransactionManager) ObjectFactory.getObject("tran");
    private UserService userService = (UserService) ObjectFactory.getObject("userServiceTarget");

    @Override
    public void register(String username, String password, String phone, String address) throws RequestParameterErrorException, UserExistException {
        try {
            // 开启事务
            // System.out.println("在执行核心业务逻辑之前执行");
            tran.begin();
            // 执行核心业务逻辑
            userService.register(username, password, phone, address);
            // int i = 1/0;
            // 提交事务
            // System.out.println("在执行核心业务逻辑之后执行");
            tran.commit();
        } catch (RequestParameterErrorException e) {
            e.printStackTrace();
            // 回滚事务
//            System.out.println("在执行核心业务逻辑之后执行");
            tran.rollback();
            throw e;
        } catch (UserExistException e) {
            e.printStackTrace();
            // 回滚事务
//            System.out.println("在执行核心业务逻辑之后执行");
            tran.rollback();
            throw e;
        } catch (Exception e) {
            e.printStackTrace();
            // 回滚事务
//            System.out.println("在执行核心业务逻辑之后执行");
            tran.rollback();
            throw e;
        }
    }

    @Override
    public User login(String username, String password) throws RequestParameterErrorException, UserNotExistException {
        try {
            tran.begin();
            User user = userService.login(username, password);
            tran.commit();
            return user;
        } catch (RequestParameterErrorException e) {
            tran.rollback();
            throw e;
        } catch (UserNotExistException e) {
            tran.rollback();
            throw e;
        }
    }

    @Override
    public void modifyPassword(User user, String oldPassword, String newPassword, String newPassword2) throws UserNotLoginException, PasswordErrorException {
        try {
            tran.begin();
            userService.modifyPassword(user, oldPassword, newPassword, newPassword2);
            tran.commit();
        } catch (UserNotLoginException e) {
            tran.rollback();
            throw e;
        } catch (PasswordErrorException e) {
            tran.rollback();
            throw e;
        }
    }
}
